package com.jade.shoesmallinterface.controller;

import com.jade.shoesmallinterface.entity.Result;
import com.jade.shoesmallinterface.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
@RequestMapping("/shoes/upload")
public class FileUploadController {

    @PostMapping("/image")
    public Result<String> uploadImage( MultipartFile file) {

        // 校验文件类型
        String contentType = file.getContentType();
        System.out.println(contentType);
        if (!contentType.startsWith("jpg")) {
            return Result.error("仅支持上传jpg图片文件");
        }
        try(InputStream inputStream = file.getInputStream()) {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 调用 AliOssUtil 类的 uploadFile 方法上传文件到 OSS
            String ossUrl = AliOssUtil.uploadFile(originalFilename, inputStream);
            // 返回 OSS 地址给前端
            return Result.success(ossUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }

    }
}